﻿#region Copyright & licence

// This file is part of Refix.
// 
// Refix is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
// 
// Refix is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public
// License along with Refix.  If not, see <http://www.gnu.org/licenses/>.
// 
// Copyright (C) 2010-11 David Musgrove and others.

#endregion

using System;
using System.Diagnostics;
using System.Linq;

using Refix.Console.Properties;
using Refix.Core;

namespace Refix.Console
{
    public class Program
    {
        public const int SUCCESS = 0;
        public const int VALIDATION_FAILURE = 1;
        public const int EXECUTION_FAILURE = 2;
        public const int CONFIGURATION_FAILURE = 3;

        static public int Main(string[] args)
        {
            bool time = args.Any(s => s == "-t");
            Stopwatch stopwatch = null;
            if (time)
            {
                args = args.Where(s => s != "-t").ToArray();
                stopwatch = new Stopwatch();
                stopwatch.Start();
            }
            if (string.IsNullOrEmpty(Configuration.LocalRepository))
            {
                OutputWriter.WriteLine(OutputVerbosity.Quiet, ResourceDispenser.GetString("PROGRAM_MISSING_CONFIGURATION"));
                return CONFIGURATION_FAILURE;
            }
            var options = new CommandWithOptions(args);
            if (!options.Command.Validate())
            {
                return VALIDATION_FAILURE;
            }
            if (!options.Command.Execute())
            {
                return EXECUTION_FAILURE;
            }
            if (time)
            {
                stopwatch.Stop();
                OutputWriter.WriteLine();
                OutputWriter.WriteLine(ResourceDispenser.GetString("PROGRAM_EXECUTION_TIME"), stopwatch.ElapsedMilliseconds / 1000f);
            }

            return SUCCESS;
        }
    }
}